import 'package:dio/dio.dart';

import 'dio_utils.dart';
import 'error_handle.dart';

class CommonNetUtil {
  static Future<dynamic> requestNetwork<T>(
    Method method, {
    required String url,
    NetSuccessCallback<T?>? onSuccess,
    NetErrorCallback? onError,
    dynamic params,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return DioUtils.instance.requestNetwork<T>(
      method,
      url,
      params: params,
      queryParameters: queryParameters,
      options: options,
      onSuccess: (data) {
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(code, msg, onError);
      },
    );
  }

  static Future<dynamic> requestNetworkGbPrinter<T>(
    Method method, {
    required String url,
    NetSuccessCallback<T?>? onSuccess,
    NetErrorCallback? onError,
    dynamic params,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return DioUtils.instance.requestNetworkGbPrinter<T>(
      method,
      url,
      params: params,
      queryParameters: queryParameters,
      options: options,
      onSuccess: (data) {
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(code, msg, onError);
      },
    );
  }

  static void asyncRequestNetwork<T>(
    Method method, {
    required String url,
    NetSuccessCallback<T?>? onSuccess,
    NetErrorCallback? onError,
    dynamic params,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    DioUtils.instance.asyncRequestNetwork<T>(
      method,
      url,
      params: params,
      queryParameters: queryParameters,
      options: options,
      onSuccess: (data) {
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(code, msg, onError);
      },
    );
  }

  static void _onError(int code, String msg, NetErrorCallback? onError) {
    if (code != ExceptionHandle.cancel_error) {
      //view.showToast(msg);
    }

    /// 页面如果dispose，则不回调onError
    if (onError != null) {
      onError(code, msg);
    }
  }
}
